<template>
  <div class="flex" style="border-bottom: 1px solid #ebeef5; padding-bottom: 10px">
    <el-button @click="handleClickReceive">
      <Icon icon="tabler:mail-down" />
      收取
    </el-button>
    <el-button @click="handleClickWrite">
      <Icon icon="bi:feather" />
      写邮件
    </el-button>
    <el-button @click="handleClickReply" :disabled="mailCurrentRow == undefined">
      <Icon icon="f7:arrowshape-turn-up-left-fill" />
      回复
    </el-button>
    <el-button @click="handleClickReplyAll" :disabled="mailCurrentRow == undefined">
      <Icon icon="f7:arrowshape-turn-up-left-2-fill" />
      回复全部
    </el-button>
    <el-button @click="handleClickForward" :disabled="mailCurrentRow == undefined">
      <Icon icon="ph:arrow-fat-line-right-fill" />
      转发
    </el-button>
    <el-button @click="handleClickDelete" :disabled="mailCurrentRow == undefined">
      <Icon icon="fluent:delete-48-filled" />
      删除
    </el-button>
  </div>
  <div style="height: calc(100vh - 170px)">
    <splitpane :min-percent="12" :default-percent="15" save-key="mailFloder">
      <template #paneL>
        <el-scrollbar>
          <el-select
            v-model="ownerUserId"
            v-if="ownerUserList.length > 0"
            class="m-2"
            style="width: 210px"
            @change="handleOwnerUserIdChange"
          >
            <el-option
              v-for="item in ownerUserList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
          <Table
            ref="folderRef"
            :data="folderList"
            :columns="folderColumns"
            :show-header="false"
            :border="false"
            row-key="id"
            alignWhole="left"
            style="--el-table-border-color: none"
            height="calc(100vh - 220px)"
            width="100%"
            align="left"
            highlight-current-row
            :expand-row-keys="folderExpandKeys"
            @expand-change="handleFolderExapandChange"
            @row-click="handleMailFolderClick"
            @row-contextmenu="handleMailFolderClick"
          >
            <template #name="{ row }">
              <div
                v-if="row.color != ''"
                class="inline-block mr-1 w-4 h-4 align-middle"
                :style="{ backgroundColor: row.color }"
              ></div>
              <Icon v-else :icon="row.icon" class="inline-block h-[13px] mr-1" />
              <span>{{ row.name }}</span>
              <span class="text-red-500 ml-1">{{ row.showCount }}</span>
            </template>
            <template #menu="{ row }">
              <context-menu-item
                v-if="handleIsShowReceiving(row)"
                label="收取"
                @click="handleMenuReceiving(row)"
              />
              <context-menu-sperator v-if="handleIsShowReceiving(row)" />
              <context-menu-item
                label="全部标为已读"
                v-if="handleIsShowAllRead(row)"
                @click="handleMenuAllRead(row)"
              />
              <context-menu-item
                label="新建文件夹"
                v-if="handleIsShowNewFolder(row)"
                @click="handleMenuNewFolder(row)"
              />
              <context-menu-item
                label="重命名"
                v-if="handleIsShowRenameFolder(row)"
                @click="handleMenuRenameFolder(row)"
              />
              <context-menu-item
                label="删除"
                v-if="handleIsShowDeleteFolder(row)"
                @click="handleMenuDeleteFolder(row)"
              />
              <context-menu-item
                label="标签管理"
                v-if="handleIsShowLabelManage(row)"
                @click="handleMenuLabelManage()"
              />
            </template>
          </Table>
        </el-scrollbar>
      </template>
      <template #paneR>
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          label-width="auto"
          class="ml-2 mt-2 query-form"
          style="border-bottom: 1px solid #ebeef5"
          v-if="isShowQueryCondition"
        >
          <el-row>
            <el-col :span="6">
              <el-form-item label="发件人" prop="fromName">
                <el-input
                  v-model="queryParams.fromName"
                  placeholder="请输入发件人"
                  :clearable="true"
                  style="width: 100% !important"
                  @keyup.enter="pageQueryMail"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收件人" prop="receiveName">
                <el-input
                  v-model="queryParams.receiveName"
                  placeholder="请输入收件人"
                  :clearable="true"
                  @keyup.enter="pageQueryMail"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="主题" prop="subject">
                <el-input
                  v-model="queryParams.subject"
                  placeholder="请输入主题"
                  :clearable="true"
                  @keyup.enter="pageQueryMail"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="全文" prop="searchContent">
                <el-input
                  v-model="queryParams.searchContent"
                  placeholder="请输入全文"
                  :clearable="true"
                  @keyup.enter="pageQueryMail"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="附件" prop="fileName">
                <el-input
                  v-model="queryParams.fileName"
                  placeholder="请输入附件名"
                  :clearable="true"
                  @keyup.enter="pageQueryMail"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签" prop="labelNames">
                <el-select
                  style="width: 100%; margin-right: 5px"
                  v-model="queryParams.labelNames"
                  multiple
                  placeholder="请选择标签"
                  collapse-tags
                  collapse-tags-tooltip
                  :max-collapse-tags="5"
                  @change="pageQueryMail"
                >
                  <el-option
                    v-for="labelItem in labelList"
                    :key="labelItem.name"
                    :label="labelItem.color"
                    :value="labelItem.name"
                  >
                    <div style="display: flex">
                      <div class="w-4 h-4 mt-[10px]" :style="{ backgroundColor: labelItem.color }">
                      </div>
                      <span style="margin-right: auto; margin-left: 7px">{{ labelItem.name }}</span>
                    </div>
                  </el-option>
                  <template #label="{ label, value }">
                    <div style="display: flex">
                      <div class="w-4 h-4 mr-1" :style="{ backgroundColor: label }"> </div>
                      <span style="font-weight: bold">{{ value }}</span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="时间" prop="sendTime">
                <el-date-picker
                  v-model="queryParams.sendTime"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div
          :style="{ height: isShowQueryCondition ? 'calc(100vh - 280px)' : 'calc(100vh - 180px)' }"
        >
          <splitpane :min-percent="15" :default-percent="20" :min-width="350" save-key="mailList">
            <template #paneL>
              <div class="w-full m-2.5 flex">
                <el-input
                  placeholder="搜索邮件"
                  v-model="queryParams.searchContent"
                  :clearable="true"
                  class="!w-[calc(100%-50px)]"
                />
                <el-button link class="mx-2.5" @click="onClickShowQueryCondition">
                  <Icon
                    :icon="
                      isShowQueryCondition ? 'mdi:chevron-double-down' : 'mdi:chevron-double-up'
                    "
                  />
                </el-button>
              </div>
              <el-scrollbar
                :style="{
                  height: isShowQueryCondition ? 'calc(100vh - 345px)' : 'calc(100vh - 240px)',
                  maxHeight: isShowQueryCondition ? 'calc(100vh - 345px)' : 'calc(100vh - 240px)'
                }"
                v-loading="mailFolderLoading"
                style="padding-right: 10px"
                ref="mailScrollbarRef"
              >
                <el-collapse
                  v-model="mailListCollapseValue"
                  v-if="mailList != undefined && mailList.length > 0"
                  @change="handleMailListExpandChange"
                >
                  <el-collapse-item
                    class="mail_list_collapse_item"
                    v-for="item in mailList"
                    :title="item.className + item.classCount"
                    :name="folderCurrentRow.id + item.id"
                    :key="folderCurrentRow.id + item.id"
                  >
                    <Table
                      :ref="'mail_table_' + item.id"
                      :data="item.mailInfo"
                      :columns="mailColumns"
                      :show-header="false"
                      row-key="id"
                      alignWhole="left"
                      align="left"
                      :border="false"
                      :showOverflowTooltip="false"
                      @row-click="(row) => handleMailClick(row, item)"
                      @row-contextmenu="(row) => handleMailClick(row, item)"
                    >
                      <template #subject="{ row }">
                        <div>
                          <div style="display: flex">
                            <el-button
                              link
                              class="w-3.5 h-3.5 px-1.5 border-0 mx-1.5"
                              @click="handleMailRead(row)"
                              v-if="row.mailType != MailboxMailTypeEnum.DRAFT"
                            >
                              <Icon
                                icon="fad:armrecording"
                                :size="14"
                                style="margin: 0"
                                :color="row.isRead ? '#e0e8f0' : '#5faff6'"
                              />
                            </el-button>
                            <el-button
                              link
                              class="w-3.5 h-3.5 px-1.5 border-0 mx-1.5"
                              @click="handleMailRead(row)"
                              v-else-if="row.isScheduled"
                            >
                              <Icon icon="ic:baseline-access-time" :size="14" style="margin: 0" />
                            </el-button>

                            <div class="w-3.5 h-3.5 px-1.5 border-0 mx-1.5" v-else></div>

                            <span
                              class="overflow-hidden text-overflow-ellipsis mr-2 text-black"
                              :class="{ 'font-bold': !row.isRead }"
                            >
                              {{ row.senderName }}
                            </span>
                            <Icon
                              icon="ic:baseline-attach-file"
                              v-if="row.isAttachment"
                              style="margin-top: 5px; transform: rotate(45deg)"
                            />
                            <span
                              class="ml-auto text-right"
                              style="color: #808080; font-size: 13px; width: auto"
                            >
                              {{ MailUtil.convertShowTime(row.showTime) }}
                            </span>
                          </div>
                          <div style="display: flex; width: 100%">
                            <el-button
                              link
                              class="w-3.5 h-3.5 px-1.5 border-0 mx-1.5"
                              @click="handleMailTop(row)"
                            >
                              <Icon
                                icon="ic:outline-star"
                                :size="15"
                                style="margin: 0"
                                :color="row.isTop ? '#ffdf83' : '#e0e8f0'"
                              />
                            </el-button>
                            <span
                              style="
                                color: #808080;
                                font-size: 13px;
                                overflow: hidden;
                                text-overflow: ellipsis;
                              "
                            >
                              {{ row.subject }}
                            </span>

                            <div
                              style="margin-left: auto; width: auto; max-width: 60%; line-height: 1"
                            >
                              <span
                                v-for="label in row.labels"
                                :key="label.labelFolder.name"
                                style="
                                  font-size: 13px;
                                  width: auto;
                                  max-width: 45px;
                                  color: white;
                                  overflow: hidden;
                                  text-overflow: ellipsis;
                                  margin-right: 1px;
                                  border-radius: 2px;
                                  display: inline-block;
                                  height: 100%;
                                  line-height: 20.5px;
                                "
                                :style="{ backgroundColor: label.labelFolder.color }"
                                class="text-right pr-1 pl-1"
                              >
                                {{ label.labelFolder.name == null ? '' : label.labelFolder.name }}
                              </span>
                            </div>
                            <el-text
                              :type="
                                approveStatusList.find((obj) => obj.value == row.approveStatus)
                                  ?.colorType
                              "
                              v-if="row.approveId"
                            >
                              {{
                                approveStatusList.find((obj) => obj.value == row.approveStatus)
                                  .label
                              }}
                            </el-text>
                          </div>
                        </div>
                      </template>
                      <template #menu="{ row }">
                        <context-menu-item
                          label="审批通过"
                          v-if="handleIsShowApprove(row)"
                          @click="handleMailApproveDone(row)"
                        />
                        <context-menu-item
                          label="审批驳回"
                          v-if="handleIsShowApprove(row)"
                          @click="handleMailApproveRevert(row)"
                        />
                        <context-menu-item
                          label="回复"
                          v-if="handleIsShowEdit(row)"
                          @click="handleClickReply"
                        />
                        <context-menu-item
                          label="回复全部"
                          v-if="handleIsShowEdit(row)"
                          @click="handleClickReplyAll"
                        />
                        <context-menu-item
                          label="转发"
                          v-if="handleIsShowEdit(row)"
                          @click="handleClickForward"
                        />
                        <context-menu-item
                          label="作为附件转发"
                          v-if="handleIsShowEdit(row)"
                          @click="handleClickForwardAsAttachment"
                        />
                        <context-menu-item
                          label="再次编辑"
                          v-if="handleIsShowEdit(row)"
                          @click="handleClickEditAgain(row)"
                        />
                        <context-menu-sperator v-if="handleIsShowEdit(row)" />
                        <context-menu-item
                          label="标为未读"
                          v-if="handleIsShowSetUnread(row)"
                          @click="handleMailRead(row)"
                        />
                        <context-menu-item
                          label="标为已读"
                          v-if="handleIsShowSetRead(row)"
                          @click="handleMailRead(row)"
                        />
                        <context-menu-item
                          label="星标置顶"
                          v-if="handleIsShowSetTop(row)"
                          @click="handleMailTop(row)"
                        />
                        <context-menu-item
                          label="取消星标置顶"
                          v-if="handleIsShowSetUntop(row)"
                          @click="handleMailTop(row)"
                        />
                        <context-menu-group label="标签管理" v-if="handleIsShowLabel(row)">
                          <context-menu-item label="清除标签" @click="handleClearMailLabel(row)" />
                          <context-menu-sperator />
                          <context-menu-item
                            v-for="labelItem in labelList"
                            :key="labelItem.name"
                            @click="handleSetMailLabel(row, labelItem.name, labelItem.color)"
                            :style="{ backgroundColor: calcLabelIsSelect(labelItem.name) }"
                          >
                            <div
                              class="w-4 h-4"
                              :style="{ backgroundColor: labelItem.color }"
                            ></div>
                            <span style="margin-right: auto; margin-left: 7px">
                              {{ labelItem.name }}
                            </span>
                          </context-menu-item>
                          <context-menu-sperator />
                          <context-menu-item label="标签管理" @click="handleMenuLabelManage()" />
                        </context-menu-group>
                        <context-menu-item
                          label="标为垃圾邮件"
                          v-if="handleIsShowSetJunk(row)"
                          @click="handleMenuSetJunk(row, true)"
                        />
                        <context-menu-item
                          label="这不是垃圾邮件"
                          v-if="handleIsShowSetNotJunk(row)"
                          @click="handleMenuSetJunk(row, false)"
                        />
                        <context-menu-item
                          label="移动到其他文件夹"
                          v-if="handleIsShowMoveFolder(row)"
                          @click="handleMenuMoveFolder(row)"
                        />
                        <context-menu-item
                          label="编辑"
                          v-if="handleIsShowDraftEdit()"
                          @click="handleDraftEdit(row)"
                        />
                        <context-menu-item
                          v-if="handleIsShowDelete(row)"
                          label="删除"
                          @click="handleMenuDelete(row)"
                        />
                      </template>
                    </Table>
                  </el-collapse-item>
                </el-collapse>
                <div
                  v-else
                  style="
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 100%;
                    height: 100%;
                    color: #b5bfc9;
                  "
                >
                  无内容
                </div>
              </el-scrollbar>
              <div style="display: flex; border-top: 1px solid #f9fafb">
                <el-pagination
                  v-model:current-page="mailPage.currentPage"
                  v-model:page-size="mailPage.pageSize"
                  :page-sizes="[500, 800, 1000]"
                  size="small"
                  layout="total, sizes, prev, pager, next"
                  :total="mailPage.totalSize"
                  :pager-count="5"
                  @change="handleMailPageChange"
                  style="margin: auto; margin-bottom: 3px; margin-top: 5px"
                />
              </div>
            </template>
            <template #paneR>
              <el-scrollbar
                ref="mailInfoScrollbarRef"
                style="height: 100%; padding: 10px"
                v-if="Object.keys(mailInfo).length > 0"
                v-loading="mailContentLoading"
              >
                <div
                  style="
                    display: flex;
                    margin-bottom: 5px;
                    margin-left: 5px;
                    font-weight: bold;
                    font-size: 20px;
                  "
                >
                  <div style="width: auto">{{
                    mailInfo?.subject == '' ? '(无主题)' : mailInfo?.subject
                  }}</div>
                  <el-button class="w-3.5 h-3.5 px-1.5 border-0 mx-1.5" link>
                    <Icon
                      icon="ic:outline-star"
                      :size="16"
                      style="margin: 0"
                      :color="mailInfo?.isTop ? '#ffdf83' : '#c9cccf'"
                    />
                  </el-button>
                  <div style="width: auto; max-width: 60%; display: flex">
                    <span
                      v-for="label in mailInfo.labels"
                      :key="label.labelFolder.name"
                      style="
                        font-size: 13px;
                        width: auto;
                        border-radius: 2px;
                        color: white;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        margin-right: 5px;
                        display: flex;
                        align-items: center;
                        height: 100%;
                      "
                      :style="{ backgroundColor: label.labelFolder.color }"
                      class="text-right pr-1 pl-1"
                    >
                      {{ label.labelFolder.name == null ? '' : label.labelFolder.name }}
                    </span>
                  </div>
                </div>
                <div style="height: auto">
                  <el-collapse v-model="activeNames" style="margin-bottom: 10px">
                    <el-collapse-item name="1">
                      <template #title>
                        <div>
                          <div
                            style="
                              font-weight: bold;
                              height: 1em;
                              text-align: left;
                              margin: 5px 5px 12px 5px;
                              line-height: 1.5em;
                            "
                          >
                            {{ mailInfo.fromName }}
                          </div>
                          <div
                            style="
                              margin: 5px;
                              text-align: left;
                              word-break: break-all;
                              line-height: 1.5em;
                            "
                            v-if="mailInfo.receiverName != ''"
                          >
                            {{ mailInfo.receiverName }}
                          </div>
                        </div>
                        <div style="margin-left: auto">
                          {{ formatDate(mailInfo.showTime, 'YYYY-MM-DD HH:mm') }}
                        </div>
                      </template>
                      <template #icon="{ isActive }">
                        <span class="icon-ele">
                          {{ isActive ? '隐藏信息' : '详细信息' }}
                        </span>
                      </template>
                      <div style="background-color: #f1f6f5; border: 1px solid #dbdfdd">
                        <div style="margin: 5px; display: -webkit-box">
                          <div style="width: 4em; text-align: right">发件人：</div>
                          <div style="display: flex; flex-wrap: wrap">
                            <div
                              style="display: flex"
                              v-for="(item, index) in mailInfo.froms"
                              :name="index"
                              :key="index"
                            >
                              <div>{{ item.name }}</div>
                              <div>&lt;{{ item.address }}></div>
                              <div v-if="index != mailInfo.froms.length - 1">, </div>
                            </div>
                          </div>
                        </div>
                        <div
                          style="margin: 5px; display: -webkit-box"
                          v-if="mailInfo.receivers.length > 0"
                        >
                          <div style="width: 4em; text-align: right">收件人：</div>
                          <div style="display: flex; flex-wrap: wrap">
                            <div
                              style="display: flex"
                              v-for="(item, index) in mailInfo.receivers"
                              :name="index"
                              :key="index"
                            >
                              <div>{{ item.name }}</div>
                              <div>&lt;{{ item.address }}></div>
                              <div v-if="index != mailInfo.receivers.length - 1">,&nbsp;</div>
                            </div>
                          </div>
                        </div>
                        <div
                          v-if="mailInfo.carbonReceivers.length > 0"
                          style="margin: 5px; display: -webkit-box"
                        >
                          <div style="width: 4em; text-align: right">抄送：</div>
                          <div style="display: flex; flex-wrap: wrap">
                            <div
                              style="display: flex"
                              v-for="(item, index) in mailInfo.carbonReceivers"
                              :name="index"
                              :key="index"
                            >
                              <div>{{ item.name }}</div>
                              <div>&lt;{{ item.address }}></div>
                              <div v-if="index != mailInfo.carbonReceivers.length - 1">,&nbsp;</div>
                            </div>
                          </div>
                        </div>

                        <div style="margin: 5px; display: -webkit-box">
                          <div style="width: 4em; text-align: right">时间：</div>
                          <div>{{ MailUtil.convertMailInfoShowTime(mailInfo.showTime) }}</div>
                        </div>
                        <div style="margin: 5px; display: -webkit-box">
                          <div style="width: 4em; text-align: right">大小：</div>
                          <div>{{ mailInfo.showSize }}</div>
                        </div>
                      </div>
                    </el-collapse-item>
                  </el-collapse>

                  <div
                    style="
                      display: flex;
                      margin: 5px 0;
                      padding-bottom: 10px;
                      border-bottom: 1px solid #ebeef5;
                    "
                    v-if="mailInfo.resources.length > 0"
                  >
                    <div
                      v-for="fileItem in mailInfo.resources"
                      :key="fileItem.name"
                      class="file-list"
                    >
                      <icon
                        :size="30"
                        style="margin: 5px"
                        :icon="MailUtil.convertFileIcon(fileItem.fileName)"
                      />
                      <div>
                        <span>{{ MailUtil.truncateFileName(fileItem.fileName) }}</span>
                        <span>{{ MailUtil.formatBytes(fileItem.size) }}</span>
                      </div>
                      <el-button link @click="handleResourceDownload(fileItem)" class="ml-auto">
                        <Icon icon="ic:outline-file-download" style="margin: 0" />
                      </el-button>
                    </div>
                  </div>
                  <el-text
                    style="
                      display: flex;
                      margin: 5px 0;
                      padding: 5px 10px;
                      border-bottom: 1px solid #ebeef5;
                      background-color: #d6ebf8;
                    "
                    v-if="mailInfo.isScheduled"
                  >
                    这封邮件将于
                    {{ formatDate(mailInfo.planSendTime, 'YYYY年MM月DD日 HH时mm分') }}
                    投递到对方邮箱。
                  </el-text>
                  <MailContent
                    v-if="isHtml(mailInfo?.content.content)"
                    :htmlContent="mailInfo?.content.content"
                  />
                  <div v-else style="white-space: pre-wrap; word-wrap: break-word; height: 100%"
                    >{{ mailInfo?.content.content }}
                  </div>
                </div>
              </el-scrollbar>
            </template>
          </splitpane>
        </div>
      </template>
    </splitpane>
  </div>
  <MailFolderNew ref="folderNewRef" @success="refreshFolderList" />
  <MailLabelManage ref="labelManageRef" @close="refreshLabel" />
  <MailMoveFolder ref="moveFolderRef" @success="moveFolderSuccess" />
  <MailReceiveTip ref="receiveTipRef" @close="closeReceiveTip" />
</template>
<script setup name="Mail" lang="ts">
import MailContent from '@/views/mailbox/mail/MailContent.vue'
import * as MailUtil from '@/views/mailbox/mail/MailUtil'
import { formatDate } from '@/utils/formatTime'
import splitpane from '@/components/ReSplitPane'
import MailLabelManage from './MailLabelManage.vue'
import MailMoveFolder from './MailMoveFolder.vue'
import MailReceiveTip from './MailReceiveTip.vue'
import * as MailboxAccountApi from '@/api/mailbox/mailboxAccount'
import * as MailApi from '@/api/mailbox/mail'
import MailFolderNew from './MailFolderNew.vue'
import * as UserApi from '@/api/system/user/user'
import * as MailApproveApi from '@/api/mailbox/mailApprove'
const { t } = useI18n() // 国际化
import { handleTree } from '@/utils/tree'
import { downloadByUrl } from '@pureadmin/utils'
import {
  MailboxFolderTypeEnum,
  MailboxFolderClassEnum,
  MailboxMailTypeEnum,
  MailboxMailApproveStatusEnum
} from '@/utils/constants'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { getKeyList } from '@pureadmin/utils'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()
const { push } = useRouter() // 路由
const { wsCache } = useCache('sessionStorage')
const instance = getCurrentInstance()!
const folderRef = ref()
const message = useMessage() // 消息弹窗
const isShowQueryCondition = ref(false)
const folderNewRef = ref()
const labelManageRef = ref()
const folderCurrentRow = ref()
const mailCurrentRow = ref()
const moveFolderRef = ref()
const mailScrollbarRef = ref()
const mailInfoScrollbarRef = ref()
const receiveTipRef = ref()
const mailInfo = ref<any>({})
const mailFolderLoading = ref(false)
const mailContentLoading = ref(false)
const queryParams = ref({
  fromName: undefined,
  receiveName: undefined,
  subject: undefined,
  searchContent: undefined,
  fileName: undefined,
  labelNames: undefined,
  sendTime: undefined,
  folderId: undefined,
  ownerId: 0,
  pageNo: 0,
  pageSize: 0
})
const mailPage = ref({
  currentPage: 1,
  pageSize: 500,
  totalSize: 0
})

const activeNames = ref(['2'])
// 邮件文件夹展开行的row id
const folderExpandKeys = ref<string[]>([])

// 常用文件夹-置顶邮件显示数量
const commonTopMailCount = ref('')

// 常用文件夹-标签文件夹列表
const commonLabelList = ref<any[]>([])

// 常用文件夹List
const commonFolderList = ref({
  id: 'common',
  name: '常用文件夹',
  icon: 'ic:outline-folder',
  showCount: '',
  folderType: MailboxFolderTypeEnum.INTERNAL,
  color: '',
  children: [
    {
      id: 'commonUnread',
      name: '所有未读',
      icon: 'ic:outline-folder',
      folderType: MailboxFolderTypeEnum.INTERNAL,
      showCount: '',
      color: ''
    },
    {
      id: 'commonTop',
      name: '置顶邮件',
      icon: 'tabler:star',
      folderType: MailboxFolderTypeEnum.INTERNAL,
      showCount: commonTopMailCount,
      color: ''
    },
    {
      id: 'commonLabel',
      name: '标签邮件',
      icon: 'streamline:interface-bookmark-bookmarks-tags-favorite',
      folderType: MailboxFolderTypeEnum.LABEL,
      showCount: '',
      color: '',
      children: commonLabelList
    },
    {
      id: 'commonReceive',
      name: '所有收件箱',
      icon: 'tabler:folder-down',
      folderType: MailboxFolderTypeEnum.INTERNAL,
      showCount: '',
      color: ''
    },
    {
      id: 'commonSend',
      name: '所有已发送',
      icon: 'tabler:folder-up',
      folderType: MailboxFolderTypeEnum.INTERNAL,
      showCount: '',
      color: ''
    },
    {
      id: 'commonAll',
      name: '所有邮件',
      icon: 'ic:outline-folder',
      folderType: MailboxFolderTypeEnum.INTERNAL,
      showCount: '',
      color: ''
    },
    {
      id: 'commonApprove',
      name: '审批邮件',
      icon: 'ic:outline-folder',
      folderType: MailboxFolderTypeEnum.INTERNAL,
      showCount: '',
      color: '',
      children: [
        {
          id: 'commonApprovePending',
          name: '待审批邮件',
          icon: 'ic:outline-folder',
          folderType: MailboxFolderTypeEnum.INTERNAL,
          showCount: '',
          color: ''
        },
        {
          id: 'commonApproveHandle',
          name: '已处理邮件',
          icon: 'ic:outline-folder',
          folderType: MailboxFolderTypeEnum.INTERNAL,
          showCount: '',
          color: ''
        },
        {
          id: 'commonApproveMy',
          name: '我提交的审批',
          icon: 'ic:outline-folder',
          folderType: MailboxFolderTypeEnum.INTERNAL,
          showCount: '',
          color: ''
        }
      ]
    }
  ]
})
const accountFolderList = ref<any[]>([])
const folderList = computed(() => {
  return [...[commonFolderList.value], ...accountFolderList.value]
})
const folderColumns: TableColumnList = [
  {
    label: '文件夹名称',
    prop: 'name',
    slot: 'name'
  }
]

const labelList = ref()

const mailList = ref()

const mailColumns: TableColumnList = [
  {
    type: 'selection',
    align: 'center',
    width: 30
  },
  {
    label: '主题',
    prop: 'subject',
    slot: 'subject',
    showOverflowTooltip: true
  }
]
const mailAccountIds = ref<any>([])
const mailListCollapseValue = ref<string[]>([])

const ownerUserList = ref<UserApi.UserVO[]>([]) // 用户列表

const ownerUserId = ref(0)

const approveStatusList = ref()

/** 初始化 */
onMounted(async () => {
  reset()
  ownerUserId.value = userStore.getUser.id
  // 获得用户列表
  ownerUserList.value = await UserApi.getOwnerUser()

  approveStatusList.value = await getIntDictOptions(DICT_TYPE.MAILBOX_MAIL_APPROVE_STATUS)
  console.log(approveStatusList.value)
  await handleOwnerUserIdChange()
})

const reset = () => {
  folderCurrentRow.value = undefined
  mailCurrentRow.value = undefined
  mailPage.value.totalSize = 0
  mailFolderLoading.value = false
  mailInfo.value = {}
  mailList.value = []
}

const handleOwnerUserIdChange = async () => {
  // 获取邮箱账号
  const mailAccounts = await MailboxAccountApi.getTopAccount(ownerUserId.value)
  // 加载标签列表
  labelList.value = await MailApi.listLabel(ownerUserId.value)
  mailAccountIds.value = []
  mailAccounts.forEach((key) => {
    mailAccountIds.value.push(key.id)
  })

  // 根据邮箱账号拉取文件夹
  await getMailFolder(mailAccountIds.value, 'all')

  // 加载展开状态
  loadFolderExpand(folderList.value)
  calcFolderUnread(accountFolderList.value)
  calcFolderUnread([commonFolderList.value.children[2]])

  reset()
}

// 加载文件夹展开状态
const loadFolderExpand = (folderList) => {
  const calcFolderExpand = (folderList) => {
    folderList.forEach((folderItem) => {
      if (folderItem.children != undefined) {
        const strId = folderItem.id.toString()
        if (getCacheMailFolderExpand(strId)) folderExpandKeys.value.push(strId)

        calcFolderExpand(folderItem.children)
      }
    })
  }
  calcFolderExpand(folderList)
}

// 收取所有账号邮件
const handleClickReceive = () => {
  receiveTipRef.value.open(mailAccountIds.value)
}

// 写邮件
const handleClickWrite = () => {
  let currentAccountId = 0
  if (folderCurrentRow.value != undefined) {
    currentAccountId = folderCurrentRow.value.accountId
  }
  push({
    name: 'MailEdit',
    state: { accountId: currentAccountId, userId: ownerUserId.value, type: 'write' }
  })
}

// 回复邮件
const handleClickReply = () => {
  let currentAccountId = 0
  if (folderCurrentRow.value != undefined) {
    currentAccountId = folderCurrentRow.value.accountId
  }
  push({
    name: 'MailEdit',
    state: {
      accountId: currentAccountId,
      userId: ownerUserId.value,
      mailId: mailCurrentRow.value.id,
      type: 'reply'
    }
  })
}

// 回复全部
const handleClickReplyAll = () => {
  let currentAccountId = 0
  if (folderCurrentRow.value != undefined) {
    currentAccountId = folderCurrentRow.value.accountId
  }
  push({
    name: 'MailEdit',
    state: {
      accountId: currentAccountId,
      userId: ownerUserId.value,
      mailId: mailCurrentRow.value.id,
      type: 'replyAll'
    }
  })
}

// 转发邮件
const handleClickForward = () => {
  let currentAccountId = 0
  if (folderCurrentRow.value != undefined) {
    currentAccountId = folderCurrentRow.value.accountId
  }
  push({
    name: 'MailEdit',
    state: {
      accountId: currentAccountId,
      userId: ownerUserId.value,
      mailId: mailCurrentRow.value.id,
      type: 'forwad'
    }
  })
}

// 作为附件转发
const handleClickForwardAsAttachment = () => {
  let currentAccountId = 0
  if (folderCurrentRow.value != undefined) {
    currentAccountId = folderCurrentRow.value.accountId
  }
  push({
    name: 'MailEdit',
    state: {
      accountId: currentAccountId,
      mailId: mailCurrentRow.value.id,
      userId: ownerUserId.value,
      type: 'forwadAsAttachment'
    }
  })
}

// 再次编辑
const handleClickEditAgain = (row) => {
  let currentAccountId = 0
  if (folderCurrentRow.value != undefined) {
    currentAccountId = folderCurrentRow.value.accountId
  }
  push({
    name: 'MailEdit',
    state: {
      accountId: currentAccountId,
      userId: ownerUserId.value,
      mailId: row.id,
      type: 'editAgain'
    }
  })
}

// 编辑邮件
const handleDraftEdit = (row) => {
  let currentAccountId = 0
  if (folderCurrentRow.value != undefined) {
    currentAccountId = folderCurrentRow.value.accountId
  }
  push({
    name: 'MailEdit',
    state: {
      accountId: currentAccountId,
      userId: ownerUserId.value,
      mailId: row.id,
      type: 'editAgain'
    }
  })
}

// 删除邮件
const handleClickDelete = () => {
  let selectRows = getMultipleSelectMail(null, instance)
  const mailIds = getKeyList(selectRows, 'id')
  deleteMail(mailIds)
}

// 删除邮件
const deleteMail = async (mailIds) => {
  await MailApi.deleteMail(mailIds)
  moveFolderSuccess(mailIds)
}

// 收取单个账号邮件
const handleMenuReceiving = async (row) => {
  receiveTipRef.value.open([row.accountId])
}

// 全部标记为已读
const handleMenuAllRead = async (row) => {
  await MailApi.setFolderAllMailRead(row.id)
  getMailFolder([row.accountId], 'single')
  refreshMailList()
}

// 新建文件夹
const handleMenuNewFolder = (row) => {
  folderNewRef.value.open({ type: 'create', folderId: row.id, accountId: row.accountId })
}

// 编辑文件夹
const handleMenuRenameFolder = (row) => {
  folderNewRef.value.open({
    type: 'rename',
    folderId: row.id,
    folderName: row.name,
    accountId: row.accountId
  })
}

// 删除文件夹
const handleMenuDeleteFolder = async (row) => {
  await message.confirm('确认要删除此文件夹吗？')
  await MailApi.deleteFolder(row.id)
  getMailFolder([row.accountId], 'single')
}

// 打开标签页面
const handleMenuLabelManage = () => {
  labelManageRef.value.open(ownerUserId.value)
}

// 是否显示搜索条件
const onClickShowQueryCondition = () => {
  isShowQueryCondition.value = !isShowQueryCondition.value
}

// 刷新文件夹
const refreshFolderList = (accountId: number) => {
  getMailFolder([accountId], 'single')
}

// 刷新邮件列表
const refreshMailList = () => {
  pageQueryMail()
}

const closeReceiveTip = (receiveAccountIds) => {
  if (receiveAccountIds.length == 1) {
    getMailFolder(receiveAccountIds, 'single')
  } else {
    getMailFolder(receiveAccountIds, 'all')
  }

  refreshMailList()
}

// 获取文件夹信息
const getMailFolder = async (accountIds: number[], getType: string) => {
  const accountFolder = await MailApi.getFolderByAccountIds(accountIds)
  accountFolder.forEach((item) => {
    // 给文件夹增加图标
    if (
      MailUtil.folderStyle[item.name] != undefined &&
      [MailboxFolderTypeEnum.INTERNAL, MailboxFolderTypeEnum.LABEL].includes(item.folderType)
    ) {
      Object.assign(item, MailUtil.folderStyle[item.name])
      item.name = t('mailbox.folder.' + item.name)
    } else {
      Object.assign(item, MailUtil.folderStyle['other'])
    }
  })
  const folderTree = handleTree(accountFolder)

  if (getType == 'all') {
    accountFolderList.value = folderTree
    // 判断文件夹是否需要展开和计算文件夹未读数量
    calcFolderUnread(folderTree)
  } else {
    //  单个更新不影响其他文件夹
    let folderIds: any[] = []
    accountFolderList.value.forEach((item) => {
      folderIds.push(item.id)
    })
    folderTree.forEach((item) => {
      // 计算文件夹未读数量
      calcFolderUnread([item])
      if (folderIds.indexOf(item.id) >= 0) {
        accountFolderList.value[folderIds.indexOf(item.id)] = item
      } else {
        accountFolderList.value.push(item)
      }
    })
  }
  // 更新置顶邮件 同步到常用文件夹
  const totalTopMailCount = await MailApi.getUnreadTopMail(accountIds)
  commonTopMailCount.value = totalTopMailCount == 0 ? '' : '(' + totalTopMailCount + ')'
  if (folderCurrentRow.value != undefined) {
    reselectFolderRow(folderRef.value.getTableRef().data)
  }
}

const reselectFolderRow = (rows) => {
  rows.forEach((row) => {
    if (row.id == folderCurrentRow.value.id) {
      folderRef.value.getTableRef().setCurrentRow(row)
    }
    if (row.children != undefined) {
      reselectFolderRow(row.children)
    }
  })
}

// 刷新标签
const refreshLabel = async () => {
  // 重新加载标签
  labelList.value = await MailApi.listLabel(ownerUserId.value)
  getMailFolder(mailAccountIds.value, 'all')
}

// 计算文件夹未读邮件数量
const calcFolderUnread = (folderTree) => {
  let totalCount = 0
  folderTree.forEach((folderItem) => {
    let showCount = (folderItem.mailCount ?? 0) - (folderItem.readMailCount ?? 0)
    let childrenCount = 0
    if (folderItem.children != undefined) childrenCount = calcFolderUnread(folderItem.children)

    if (folderExpandKeys.value.indexOf(folderItem.id.toString()) < 0) showCount += childrenCount
    folderItem.showCount = showCount > 0 ? '(' + showCount + ')' : ''
    // 账号文件夹计算收件箱和其它文件夹的未读邮件数量
    if (
      !(
        folderItem.folderType == MailboxFolderTypeEnum.INTERNAL &&
        [
          t('mailbox.folder.draft'),
          t('mailbox.folder.send'),
          t('mailbox.folder.delete'),
          t('mailbox.folder.junk')
        ].includes(folderItem.name)
      ) &&
      folderItem.folderType != MailboxFolderTypeEnum.LABEL
    )
      totalCount += showCount
  })
  return totalCount
}

watch(labelList, (newLabelList) => {
  commonLabelList.value = []
  newLabelList.forEach((label) => {
    commonLabelList.value.push({
      id: 'commonChildLabel-' + label.id,
      name: label.name,
      color: label.color,
      sort: label.sort,
      mailCount: 0,
      readMailCount: 0
    })
  })
})

/* 常用文件夹下各个文件夹显示的数量计算逻辑
    所有未读 ： 包括收取箱和其他文件夹(包括子文件夹)的未读邮件 不包含垃圾邮件、标签邮件
    置顶邮件：显示置顶邮件(包括子文件夹)中未读邮件的数量
    标签邮件：显示标签邮件(包括子文件夹)中未读邮件的数量
    所有收件箱： 显示收件箱文件夹(包括子文件夹)中未读邮件的数量
    所有已发送：不需要显示(包括子文件夹)
    所有邮件：显示所有邮件(包括子文件夹)的未读邮件数量 包括垃圾邮件、其他文件夹 但不包含标签邮件
*/
watch(
  () => accountFolderList.value,
  (newAccountFolderList) => {
    let totalMailCount = 0
    let totalUnreadMailCount = 0
    let totalReceiveMailCount = 0
    let totalLabelMailCount = 0
    commonLabelList.value.forEach((commonLabelItem) => {
      commonLabelItem.mailCount = 0
      commonLabelItem.readMailCount = 0
    })
    // 各个邮箱账号的收件箱和垃圾邮件未读数量
    newAccountFolderList.forEach((accountFolderItem) => {
      accountFolderItem.children.forEach((folderItem) => {
        const itemUnreadMailCount = getUnreadCount(folderItem)
        if (folderItem.name == t('mailbox.folder.label')) {
          if (folderItem.children != undefined) {
            folderItem.children.forEach((labelItem) => {
              commonLabelList.value.forEach((commonLabelItem) => {
                if (commonLabelItem.name == labelItem.name) {
                  commonLabelItem.mailCount += labelItem.mailCount
                  commonLabelItem.readMailCount += labelItem.readMailCount
                  const showCount = commonLabelItem.mailCount - commonLabelItem.readMailCount
                  commonLabelItem.showCount = showCount > 0 ? '(' + showCount + ')' : ''
                }
              })
            })
          }
          totalLabelMailCount += itemUnreadMailCount
        } else {
          totalMailCount += itemUnreadMailCount
          if (folderItem.name != t('mailbox.folder.junk'))
            totalUnreadMailCount += itemUnreadMailCount
          if (folderItem.name == t('mailbox.folder.receive'))
            totalReceiveMailCount += itemUnreadMailCount
        }
      })
    })
    // 更新各种邮件类型的总数量， 加载常用文件夹-标签邮件
    commonFolderList.value.children.forEach((childFolder) => {
      if (childFolder.id == 'commonLabel')
        childFolder.showCount = totalLabelMailCount == 0 ? '' : '(' + totalLabelMailCount + ')'
      if (childFolder.id == 'commonUnread')
        childFolder.showCount = totalUnreadMailCount == 0 ? '' : '(' + totalUnreadMailCount + ')'
      if (childFolder.id == 'commonReceive')
        childFolder.showCount = totalReceiveMailCount == 0 ? '' : '(' + totalReceiveMailCount + ')'
      if (childFolder.id == 'commonAll')
        childFolder.showCount = totalMailCount == 0 ? '' : '(' + totalMailCount + ')'
    })
  },
  { deep: true }
)

// 获取文件夹未读数量
const getUnreadCount = (folderItem) => {
  if (folderItem.mailCount == undefined || folderItem.readMailCount == undefined) return 0
  let unreadCount = folderItem.mailCount - folderItem.readMailCount
  if (folderItem.children != undefined && Array.isArray(folderItem.children)) {
    folderItem.children.forEach((childItem) => {
      // 标签文件夹不计算子标签的未读数量，使用标签文件夹表的邮件数量和已读邮件数量
      if (childItem.folderType != MailboxFolderTypeEnum.LABEL)
        unreadCount += getUnreadCount(childItem)
    })
  }
  return unreadCount
}

// 处理文件夹是否展开
const handleFolderExapandChange = (row, expanded) => {
  const strId = row.id.toString()
  if (expanded) folderExpandKeys.value.push(strId)
  else {
    if (folderExpandKeys.value.indexOf(strId) >= 0)
      folderExpandKeys.value.splice(folderExpandKeys.value.indexOf(strId), 1)
  }
  setCacheMailFolderExpand(strId, expanded)

  // 通用标签文件夹不计算子文件夹的数量，通用标签文件夹 = SUM(每个账号的标签文件夹)
  if (row.id != 'commonLabel') calcFolderUnread([row])

  // 如果折叠的文件夹里包含被选中的文件夹，那么自动选中折叠的文件夹
  if (!expanded && folderCurrentRow.value != undefined) {
    if (judgeChildIsSelected(row)) {
      folderRef.value.getTableRef().setCurrentRow(row)
      handleMailFolderClick(row)
    }
  }
}

const judgeChildIsSelected = (row) => {
  let isChildSelected = false
  if (row.children == undefined) return false
  row.children.forEach((item) => {
    if (item.id == folderCurrentRow.value.id) {
      isChildSelected = true
    }
    if (item.children != undefined && judgeChildIsSelected(item)) {
      isChildSelected = true
    }
  })
  return isChildSelected
}

// 将文件夹展开状态记录到缓存
const setCacheMailFolderExpand = (id: string, isExpand: boolean) => {
  let mailFolderExpandIds = wsCache.get(CACHE_KEY.MAIL_FOLDER_EXPAND)
  if (isExpand) {
    if (mailFolderExpandIds == undefined) mailFolderExpandIds = [id]
    else if (mailFolderExpandIds.indexOf(id) < 0) mailFolderExpandIds.push(id)
  } else {
    if (mailFolderExpandIds == undefined) return
    if (mailFolderExpandIds.indexOf(id) >= 0)
      mailFolderExpandIds.splice(mailFolderExpandIds.indexOf(id), 1)
  }
  wsCache.set(CACHE_KEY.MAIL_FOLDER_EXPAND, mailFolderExpandIds)
}

// 从缓存中获取文件夹展开状态
const getCacheMailFolderExpand = (id: string) => {
  const mailFolderExpandIds = wsCache.get(CACHE_KEY.MAIL_FOLDER_EXPAND)
  if (mailFolderExpandIds == undefined) return false

  if (mailFolderExpandIds.indexOf(id) >= 0) return true
  return false
}

const handleMailListExpandChange = (activeNames) => {
  setCacheMailListExpand(activeNames)
}

// 将邮件列表展开状态记录到缓存
const setCacheMailListExpand = (activeNames) => {
  //将折叠的列记录到缓存
  let mailListExpandIds = wsCache.get(CACHE_KEY.MAIL_LIST_EXPAND)
  mailList.value.forEach((mailItem) => {
    const callapseItemId = folderCurrentRow.value.id + mailItem.id
    if (activeNames.indexOf(callapseItemId) >= 0) {
      if (mailListExpandIds == undefined) return
      if (mailListExpandIds.indexOf(callapseItemId) >= 0)
        mailListExpandIds.splice(mailListExpandIds.indexOf(callapseItemId), 1)
    } else {
      if (mailListExpandIds == undefined) mailListExpandIds = [callapseItemId]
      else if (mailListExpandIds.indexOf(callapseItemId) < 0) mailListExpandIds.push(callapseItemId)
    }
  })
  wsCache.set(CACHE_KEY.MAIL_LIST_EXPAND, mailListExpandIds)
}

// 从缓存中获取邮件列表展开状态
const getCacheMailListExpand = (id: string) => {
  const mailListExpandIds = wsCache.get(CACHE_KEY.MAIL_LIST_EXPAND)
  if (mailListExpandIds == undefined) return false

  if (mailListExpandIds.indexOf(id) >= 0) return true
  return false
}

// 分页查询邮件
const pageQueryMail = async () => {
  mailFolderLoading.value = true
  try {
    queryParams.value.folderId = folderCurrentRow.value.id
    queryParams.value.pageNo = mailPage.value.currentPage
    queryParams.value.pageSize = mailPage.value.pageSize
    queryParams.value.ownerId = ownerUserId.value

    const pageMailInfo = await MailApi.pageMail(queryParams.value)
    const folderMailList = pageMailInfo.list
    console.log(folderMailList)
    mailPage.value.totalSize = pageMailInfo.total
    let classMailList: Record<string, any[]> = {}
    let classMailClassList: string[] = []
    const mailClassKeys = Object.keys(MailUtil.mailClass)
    mailClassKeys.forEach((key) => {
      classMailList[key] = []
      classMailClassList.push(key)
    })
    folderMailList.forEach((item) => {
      // 收件使用收件时间 发件使用发送时间 草稿使用上次修改时间
      item.showTime =
        item.mailType == MailboxMailTypeEnum.SEND
          ? item.sendTime
          : item.mailType == MailboxMailTypeEnum.RECEIVE
          ? item.receiveTime
          : item.updateTime
      if (item.subject == '') item.subject = '(无主题)'
      if (item.senderName == '') {
        if (item.froms != undefined && item.froms.length >= 1) item.senderName = item.froms[0].name
        else item.senderName = '<无收件人>'
      }
      if (item.isTop) {
        classMailList.top.push(item)
      } else {
        const dateType = MailUtil.calcMailTimeType(item.showTime)
        if (dateType != 'error') {
          if (!classMailList[dateType]) {
            classMailList[dateType] = []
            classMailClassList.push(dateType)
          }
          classMailList[dateType].push(item)
        }
      }
    })
    mailList.value = []
    classMailClassList.forEach((item) => {
      if (classMailList[item] != undefined && classMailList[item].length > 0) {
        mailList.value.push({
          id: item,
          className: MailUtil.convertMailClass(item),
          classCount: '(' + classMailList[item].length + ')',
          mailInfo: classMailList[item]
        })
        if (!getCacheMailListExpand(folderCurrentRow.value.id + item))
          mailListCollapseValue.value.push(folderCurrentRow.value.id + item)
      }
    })
    if (Object.keys(mailInfo.value).length > 0) {
      let isExists = false
      mailList.value.forEach((item) => {
        const tableMail = instance?.proxy?.$refs['mail_table_' + item.id]
        if (tableMail != undefined && tableMail[0] != undefined) {
          tableMail[0].getTableRef().data.forEach((row) => {
            if (row.id == mailInfo.value.id) {
              tableMail[0].getTableRef().setCurrentRow(row)
              isExists = true
            }
          })
        }
      })
      if (!isExists) mailInfo.value = {}
    }
  } finally {
    mailFolderLoading.value = false
    setTimeout(() => {
      mailScrollbarRef.value.update()
    }, 10)
  }
}

// 点击文件夹
const handleMailFolderClick = (row) => {
  folderCurrentRow.value = row
  pageQueryMail()
}

// 点击邮件
const handleMailClick = async (row, curMailInfo) => {
  if (row.id == mailInfo.value.id) return
  mailCurrentRow.value = row
  mailContentLoading.value = true
  try {
    // 点击某一行 将其他mailTable的行设置为未选中
    mailList.value.forEach((item) => {
      const tableMail = instance?.proxy?.$refs['mail_table_' + item.id]
      if (tableMail != undefined && item.id != curMailInfo.id)
        tableMail[0].getTableRef().setCurrentRow()
    })
    mailInfo.value = await MailApi.getMailDetail(row.id)
    mailInfo.value.showTime =
      mailInfo.value.mailType == MailboxMailTypeEnum.SEND
        ? mailInfo.value.sendTime
        : mailInfo.value.mailType == MailboxMailTypeEnum.RECEIVE
        ? mailInfo.value.receiveTime
        : mailInfo.value.updateTime

    mailInfo.value.showSize = MailUtil.formatBytes(mailInfo.value.size)
    mailInfo.value.fromName = ''
    mailInfo.value.froms.forEach((from) => {
      if (mailInfo.value.fromName != '') mailInfo.value.fromName += ', '
      mailInfo.value.fromName += from.name
    })
    if (mailInfo.value.receivers.length > 0) {
      mailInfo.value.receiverName = '发给 '
      mailInfo.value.receivers.forEach((receiver) => {
        if (mailInfo.value.receiverName != '发给 ') mailInfo.value.receiverName += ', '
        mailInfo.value.receiverName += receiver.name
      })
    }

    mailInfo.value.carbonReceivers.forEach((carbonReceiver) => {
      if (mailInfo.value.receiverName != '发给 ') mailInfo.value.receiverName += ', '
      mailInfo.value.receiverName += carbonReceiver.name
    })
    if (!row.isRead) {
      row.isRead = true
      getMailFolder([row.accountId], 'single')
    }
  } finally {
    mailContentLoading.value = false
    setTimeout(() => {
      mailInfoScrollbarRef.value.setScrollTop(0)
    }, 10)
  }
}

// 判断邮件内容是否是html格式
const isHtml = (str) => {
  const htmlRegex = /<[^>]+>/
  if (!htmlRegex.test(str)) {
    return false
  } else {
    return true
  }
}

// 设置邮件置顶或非置顶
const handleMailTop = async (row) => {
  // 记录开始时间
  const setTopStatus = !row.isTop
  let selectRows = getMultipleSelectMail(row, instance)

  let updateMailList: Record<string, any[]> = {}
  let mailClassList: string[] = []

  let rowIds: any[] = getKeyList(selectRows, 'id')
  // 将选中的邮件从mailList中剔除 并保存在updateMailList
  mailList.value = mailList.value.filter((mailClassItem) => {
    mailClassItem.mailInfo = mailClassItem.mailInfo.filter((mailInfoItem) => {
      if (rowIds.includes(mailInfoItem.id) && mailInfoItem.isTop != setTopStatus) {
        if (setTopStatus) {
          if (!updateMailList.top) {
            updateMailList['top'] = []
            mailClassList.push('top')
          }
          updateMailList.top.push(mailInfoItem)
        } else {
          const dateType = MailUtil.calcMailTimeType(mailInfoItem.showTime)
          if (dateType != 'error') {
            if (!updateMailList[dateType]) {
              updateMailList[dateType] = []
              mailClassList.push(dateType)
            }
            updateMailList[dateType].push(mailInfoItem)
          }
        }
        mailInfoItem.isTop = setTopStatus
        return false
      } else {
        return true
      }
    })
    // 原来的分类邮件数量为0则删除 不为0重新计算邮件数量
    if (mailClassItem.mailInfo.length == 0) return false
    else {
      mailClassItem.classCount = '(' + mailClassItem.mailInfo.length + ')'
      return true
    }
  })
  // 将classMailList的邮件插入到正确的mailItem里
  mailClassList.forEach((classItem) => {
    if (updateMailList[classItem] != undefined && updateMailList[classItem].length > 0) {
      const isExists = mailList.value.filter((mailItem) => {
        if (mailItem.id == classItem) {
          updateMailList[classItem].forEach((classMailItem) => {
            let index = 0
            mailItem.mailInfo.forEach((mailInfoItem) => {
              if (dayjs(mailInfoItem.showTime).isBefore(dayjs(classMailItem.showTime))) return
              else index++
            })
            mailItem.mailInfo.splice(index, 0, classMailItem)
            mailItem.classCount = '(' + mailItem.mailInfo.length + ')'
          })
          return true
        } else {
          return false
        }
      })
      // 重新计算各个分类的邮件数量
      if (isExists.length == 0) {
        mailList.value.splice(calcMailClassIndex(mailList.value, classItem), 0, {
          id: classItem,
          className: MailUtil.convertMailClass(classItem),
          classCount: '(' + updateMailList[classItem].length + ')',
          mailInfo: updateMailList[classItem]
        })
      }
    }
  })
  // 记录结束时间并输出
  await MailApi.setMailTop({ ids: rowIds, isTop: setTopStatus })
  row.isTop = setTopStatus
}

// 计算mailClassItem在邮件分类的插入位置
const calcMailClassIndex = (mailList, mailClassItem) => {
  let index = 0
  const keys = Object.keys(MailUtil.mailClass)
  mailList.some((item) => {
    if (MailUtil.mailClass[item.id] == undefined && MailUtil.mailClass[mailClassItem] != undefined)
      return true
    if (
      MailUtil.mailClass[item.id] != undefined &&
      MailUtil.mailClass[mailClassItem] != undefined &&
      keys.indexOf(item.id) > keys.indexOf(mailClassItem)
    )
      return true
    if (
      MailUtil.mailClass[item.id] == undefined &&
      MailUtil.mailClass[mailClassItem] == undefined &&
      item < mailClassItem
    )
      return true
    index++
  })
  return index
}

// 获取邮件列表选中的行
const getMultipleSelectMail = (row, instance) => {
  let selectRows: any[] = []
  // 查找多选的行
  mailList.value.forEach((item) => {
    const tableMail = instance?.proxy?.$refs['mail_table_' + item.id]
    if (tableMail != undefined && tableMail.length > 0) {
      selectRows = selectRows.concat(tableMail[0].getTableRef().getSelectionRows())
    }
  })
  if (row != null && !selectRows.includes(row)) selectRows.push(row)
  return selectRows
}

// 处理邮件已读或未读
const handleMailRead = async (row) => {
  let selectRows = getMultipleSelectMail(row, instance)
  const setReadStatus = !row.isRead
  let rowIds: any[] = getKeyList(selectRows, 'id')
  await MailApi.setMailRead({ ids: rowIds, isRead: setReadStatus })
  selectRows.forEach((row) => {
    row.isRead = setReadStatus
  })

  getMailFolder([folderCurrentRow.value.accountId], 'single')
}

// 清除邮件标签
const handleClearMailLabel = async (row) => {
  let selectRows = getMultipleSelectMail(row, instance)
  let rowIds: any[] = getKeyList(selectRows, 'id')
  await MailApi.clearMailLabel({ ids: rowIds })
  selectRows.forEach((row) => {
    row.labels = []
  })
  getMailFolder(getKeyList(selectRows, 'accountId'), 'single')
}

// 设置邮件标签
const handleSetMailLabel = async (row, labelName, labelColor) => {
  let selectRows = getMultipleSelectMail(row, instance)
  let rowIds: any[] = getKeyList(selectRows, 'id')
  let isAdd = true
  if (mailCurrentRow.value.labels != undefined) {
    mailCurrentRow.value.labels.forEach((label) => {
      if (label.labelFolder.name == labelName) isAdd = false
    })
  }
  await MailApi.setMailLabel({ ids: rowIds, labelName: labelName, isAdd: isAdd })
  selectRows.forEach((row) => {
    if (isAdd) {
      if (row.labels == undefined || row.labels.length == 0)
        row.labels = [{ labelFolder: { name: labelName, color: labelColor } }]
      else row.labels.push({ labelFolder: { name: labelName, color: labelColor } })
    } else {
      if (row.labels.length > 0) {
        row.labels = row.labels.filter((label) => {
          return label.labelFolder.name != labelName
        })
      }
    }
  })
  getMailFolder(getKeyList(selectRows, 'accountId'), 'single')
}

// 邮件移动文件夹
const handleMenuMoveFolder = (row) => {
  let selectRows = getMultipleSelectMail(row, instance)
  let rowIds: any[] = getKeyList(selectRows, 'id')
  moveFolderRef.value.open({ mailIds: rowIds, accountId: row.accountId })
}

// 邮件移动文件夹成功后刷新
const moveFolderSuccess = (mailIds) => {
  let accountIds: any[] = []
  mailList.value = mailList.value.filter((item) => {
    item.mailInfo = item.mailInfo.filter((infoItem) => {
      if (mailIds.includes(infoItem.id)) {
        accountIds.push(infoItem.accountId)
        return false
      }
      return true
    })
    if (item.mailInfo.length == 0) return false
    else return true
  })
  getMailFolder(accountIds, 'single')
}

// 设置邮件为垃圾邮件
const handleMenuSetJunk = async (row, isJunk) => {
  let selectRows = getMultipleSelectMail(row, instance)
  const mailIds = getKeyList(selectRows, 'id')
  await MailApi.setMailJunk({ mailIds: mailIds, isJunk: isJunk })
  moveFolderSuccess(mailIds)
}

// 删除邮件
const handleMenuDelete = (row) => {
  let selectRows = getMultipleSelectMail(row, instance)
  const mailIds = getKeyList(selectRows, 'id')
  deleteMail(mailIds)
}

// 查询邮件列表
const handleMailPageChange = () => {
  pageQueryMail()
}

// 计算标签是否选中
const calcLabelIsSelect = (labelName) => {
  let backgroundColor = 'none'
  if (mailCurrentRow.value.labels != undefined) {
    mailCurrentRow.value.labels.forEach((label) => {
      if (label.labelFolder.name == labelName) backgroundColor = '#439166'
    })
  }

  return backgroundColor
}

const handleResourceDownload = (fileItem) => {
  downloadByUrl(fileItem.urlName, fileItem.fileName)
}

// 设置邮件审批通过
const handleMailApproveDone = async (row) => {
  let selectRows = getMultipleSelectMail(row, instance)
  let approveIds = getKeyList(selectRows, 'approveId')
  await MailApproveApi.done({ ids: approveIds })
  message.success('审批成功')
  refreshMailList()
}

// 设置邮件审批驳回
const handleMailApproveRevert = async (row) => {
  let selectRows = getMultipleSelectMail(row, instance)
  let approveIds = getKeyList(selectRows, 'approveId')
  await MailApproveApi.revert({ ids: approveIds })
  message.success('驳回成功')
  refreshMailList()
}

// 判断是否显示收取邮件按钮
const handleIsShowReceiving = (row) => {
  return row.folderType == MailboxFolderTypeEnum.ACCOUNT
}

// 判断是否显示全部标记为已读按钮
const handleIsShowAllRead = (row) => {
  return row.folderType != MailboxFolderTypeEnum.ACCOUNT
}

// 判断是否显示新建文件夹按钮
const handleIsShowNewFolder = (row) => {
  if (row.id > 0 && row.folderType != MailboxFolderTypeEnum.LABEL) return true
  else return false
}

// 判断是否显示重命名按钮
const handleIsShowRenameFolder = (row) => {
  if (row.id > 0 && row.folderType == MailboxFolderTypeEnum.EDIT) return true
  else return false
}

// 判断是否显示删除按钮
const handleIsShowDeleteFolder = (row) => {
  if (row.id > 0 && row.folderType == MailboxFolderTypeEnum.EDIT) return true
  else return false
}

// 判断是否显示标签管理按钮
const handleIsShowLabelManage = (row) => {
  if (row.folderType == MailboxFolderTypeEnum.LABEL) return true
  else return false
}

// 判断是否显示编辑按钮
const handleIsShowEdit = (row) => {
  if (folderCurrentRow.value.folderClass == MailboxFolderClassEnum.DRAFT || row.approveId)
    return false
  else return true
}

const handleIsShowDelete = (row) => {
  if (row.approveId) return false
  else return true
}

// 判断是否显示标为未读按钮
const handleIsShowSetUnread = (row) => {
  if (
    folderCurrentRow.value.folderClass != MailboxFolderClassEnum.DRAFT &&
    row.isRead &&
    row.approveId == null
  )
    return true
  else return false
}

// 判断是否显示标为已读按钮
const handleIsShowSetRead = (row) => {
  if (
    folderCurrentRow.value.folderClass != MailboxFolderClassEnum.DRAFT &&
    !row.isRead &&
    row.approveId == null
  )
    return true
  else return false
}

// 判断是否显示置顶按钮
const handleIsShowSetTop = (row) => {
  if (
    folderCurrentRow.value.folderClass == MailboxFolderClassEnum.DRAFT ||
    row.isTop ||
    row.approveId
  )
    return false
  else return true
}

// 判断是否显示取消置顶按钮
const handleIsShowSetUntop = (row) => {
  if (
    folderCurrentRow.value.folderClass == MailboxFolderClassEnum.DRAFT ||
    !row.isTop ||
    row.approveId
  )
    return false
  else return true
}

// 判断是否标签管理
const handleIsShowLabel = (row) => {
  if (folderCurrentRow.value.folderClass == MailboxFolderClassEnum.DRAFT || row.approveId)
    return false
  else return true
}

// 判断是否显示标为垃圾邮件按钮
const handleIsShowSetJunk = (row) => {
  if (folderCurrentRow.value.folderClass == MailboxFolderClassEnum.JUNK || row.approveId)
    return false
  else return true
}

// 判断是否显示不是垃圾邮件按钮
const handleIsShowSetNotJunk = (row) => {
  if (folderCurrentRow.value.folderClass == MailboxFolderClassEnum.JUNK && row.approveId == null)
    return true
  else return false
}

// 判断是否显示移动到其他文件夹按钮
const handleIsShowMoveFolder = (row) => {
  if (folderCurrentRow.value.folderClass == MailboxFolderClassEnum.DRAFT || row.approveId)
    return false
  else return true
}

// 判断是否显示编辑按钮
const handleIsShowDraftEdit = () => {
  if (folderCurrentRow.value.folderClass == MailboxFolderClassEnum.DRAFT) return true
  else return false
}

// 判断是否显示审批按钮
const handleIsShowApprove = (row) => {
  if (row.approveStatus && row.approveStatus == MailboxMailApproveStatusEnum.PENDING_APPROVAL)
    return true
  else return false
}
</script>
<style scoped>
.mail_list_collapse_item :deep(.el-collapse-item__content) {
  padding-bottom: 0;
}
:deep(.el-collapse-item__wrap) {
  border: none;
}
.mail_list_collapse_item :deep(.el-collapse-item__header) {
  font-size: smaller;
  height: 2em;
  border-bottom: 1px #ebeef5 solid;
  padding-left: 10px;
}
:deep(.el-popper) {
  display: none;
}
.query-form :deep(.el-input),
.query-form :deep(.el-date-editor) {
  width: 100% !important;
  margin-right: 5px;
}
.icon-ele {
  margin: 0 8px 0 3px;
  color: #409eff;
  width: 5em;
}
:deep(.el-collapse-item__header) {
  height: auto;
}
:deep(.el-pagination__sizes) {
  margin: 0;
}
:deep(.el-pagination .btn-prev) {
  margin: 0;
}
:deep(.el-table) {
  --el-table-current-row-bg-color: #d9eaff;
}

.file-list {
  border: 0.5px solid #eaeaea;
  width: 200px;
  min-width: 200px;
  display: flex;
  flex-wrap: wrap;
  margin-right: 8px;
}
.file-list > div {
  overflow: hidden;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: left; /* 水平居中对齐 */
  justify-content: center; /* 垂直居中对齐 */
}

.file-list span {
  cursor: default;
  font-size: 10pt;
}
</style>
